package mailclient.system;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import cn.boot.entity.Words;
import mailclient.mail.MailLoader;
import mailclient.mail.MailLoaderImpl;
import mailclient.mail.MailSender;
import mailclient.mail.MailSenderImpl;
import mailclient.object.Mail;
import mailclient.util.FileUtil;

public class MainFrame {

	//收件箱的Mail对象集合，代表所有在收件箱中的邮件
	public List<Mail>			inMails;
	//发件箱的邮件集合
	public List<Mail>			outMails;
	//成功发送的邮件集合
	public List<Mail>			sentMails;
	//草稿箱的邮件集合
	public List<Mail>			draftMails;
	//垃圾箱的邮件集合
	public List<Mail>			deleteMails;
	//垃圾邮件的邮件集合
	public List<Mail>			spamMails;
	//当前界面列表所显示的对象
	public List<Mail>			currentMails;

	//邮箱加载对象
	private MailLoader		mailLoader			= new MailLoaderImpl();
	//本地中的邮件处理对象
	private SystemHandler	systemHandler		= new SystemHandlerImpl();
	//本地中的邮件加载对象
	private SystemLoader	systemLoader		= new SystemLoaderImpl();
	//发送邮件对象
	private MailSender		mailSender			= new MailSenderImpl();
	//当前打开的文件对象
	private Mail					currentMail;
	//接收邮件的间隔, 单位毫秒
	private long					receiveInterval	= 1000 * 3000;

	private MailContext		ctx;

	Timer									timer						= new Timer();

	public List<Words>		words						= new ArrayList<Words>();

	public MainFrame(MailContext ctx) {
		this.ctx = ctx;
		//初始化各个列表集合
		initMails();
		//设置当前显示的邮件集合为收件箱的集合
		this.currentMails = this.inMails;
		timer.schedule(new ReceiveTask(this), 10000, this.receiveInterval);
	}

	public SystemHandler getSystemHandler() {
		return this.systemHandler;
	}

	public MailSender getMailSender() {
		return this.mailSender;
	}

	private boolean noSelectData(Mail mail) {
		if (mail == null) {
			showMessage("请选择需要操作的数据");
			return true;
		}
		return false;
	}

	//发送一封邮件
	private void send() {
		Mail mail = getSelectMail();
		if (noSelectData(mail))
			return;
		if (isReceive(mail)) {
			showMessage("收件箱的邮件不能发送");
			return;
		}
	}

	//回复邮件
	private void reply() {
		Mail mail = getSelectMail();
		if (noSelectData(mail))
			return;
		//需要判断回复邮件是否在收件箱中
		if (!isReceive(mail)) {
			showMessage("只能回复收件箱中的邮件");
			return;
		}
	}

	//判断邮件是否在收件箱中
	private boolean isReceive(Mail mail) {
		for (Mail m : this.inMails) {
			if (m.getXmlName().equals(mail.getXmlName()))
				return true;
		}
		return false;
	}

	//转发
	private void transmit() {
		Mail mail = getSelectMail();
		if (noSelectData(mail))
			return;
	}

	//还原邮件
	public void revert() {
		Mail mail = getSelectMail();
		if (noSelectData(mail))
			return;
		//垃圾箱包含这个Mail对象才进行还原
		if (this.deleteMails.contains(mail)) {
			//从垃圾箱集合中删除
			this.deleteMails.remove(mail);
			//操作文件, 并deleted目录中的xml中
			this.systemHandler.revert(mail, this.ctx);
			//还原到各个集合中
			revertMailToList(mail);
		}
		this.currentMail = null;
		refreshTable();
	}

	//还原Mail对象到各个相应的集合
	private void revertMailToList(Mail mail) {
		if (mail.getFrom().equals(FileUtil.INBOX)) {
			this.inMails.add(mail);
		} else if (mail.getFrom().equals(FileUtil.SENT)) {
			this.sentMails.add(mail);
		} else if (mail.getFrom().equals(FileUtil.DRAFT)) {
			this.draftMails.add(mail);
		} else if (mail.getFrom().equals(FileUtil.OUTBOX)) {
			this.outMails.add(mail);
		}
	}

	//删除邮件
	public void delete() {
		Mail mail = getSelectMail();
		if (noSelectData(mail))
			return;
		//判断垃圾箱中是否有该份邮件(已经被放到垃圾箱中), 有的话不进行处理
		if (!this.deleteMails.contains(mail)) {
			//从当前的集合中删除
			this.currentMails.remove(mail);
			//加到垃圾箱的集合中
			this.deleteMails.add(0, mail);
			//将邮件对应的xml文件放到deleted的目录中
			this.systemHandler.delete(mail, this.ctx);
		}
		this.currentMail = null;
		//刷新列表
		refreshTable();
	}

	//彻底删除一封邮件
	private void realDelete() {
		Mail mail = getSelectMail();
		if (noSelectData(mail))
			return;
		//从当前的集合中删除 
		this.currentMails.remove(mail);
		//删除xml文件和对应的附件
		this.systemHandler.realDelete(mail, this.ctx);
		this.currentMail = null;
		refreshTable();
	}

	//获得列表中所选行的xmlName列的值（该值是唯一的）
	private String getSelectXmlName() {
		return null;
	}

	//获取在列表中所选择的Mail对象
	private Mail getSelectMail() {
		String xmlName = getSelectXmlName();
		return getMail(xmlName, this.currentMails);
	}

	//从集合中找到xmlName与参数一致的Mail对象
	private Mail getMail(String xmlName, List<Mail> mails) {
		for (Mail m : mails) {
			if (m.getXmlName().equals(xmlName))
				return m;
		}
		return null;
	}

	//初始化时创建各个box中的数据
	private void initMails() {
		this.inMails = this.systemLoader.getInBoxMails(this.ctx);
		this.draftMails = this.systemLoader.getDraftBoxMails(this.ctx);
		this.deleteMails = this.systemLoader.getDeletedBoxMails(this.ctx);
		this.outMails = this.systemLoader.getOutBoxMails(this.ctx);
		this.sentMails = this.systemLoader.getSentBoxMails(this.ctx);
		this.spamMails = this.systemLoader.getSpamBoxMails(this.ctx);
	}

	/*
	 * TODO 到服务器中收取邮件
	 */
	public void receive() {
		try {
			System.out.println("接收邮件");
			List<Mail> newMails = this.mailLoader.getMessages(this.ctx);
			System.out.println("数量:" + newMails.size());
			List<Mail> spamMails_ = new ArrayList<Mail>();
			if (newMails.size() > 0) {
				List<Words> wlist = words;
				Iterator<Mail> iter = newMails.iterator();
				while (iter.hasNext()) {
					Mail m = iter.next();
					for (Words w : wlist) {
						if (m.getContent().contains(w.getName())) {
							spamMails_.add(m);
							m.setFrom("spam");
							iter.remove();
							break;
						}
					}
				}
			}
			//得到Mail对象, 添加到inMails集合中
			this.inMails.addAll(0, newMails);
			//保存到本地的收件箱中
			saveToInBox(newMails);

			this.spamMails.addAll(0, spamMails_);
			saveToSpamBox(spamMails_);
			//刷新列表
			refreshTable();
		} catch (Exception e) {
			e.printStackTrace();
			showMessage(e.getMessage());
		}
	}

	private int showMessage(String s) {
		System.out.println(s);
		return 0;
	}

	//保存到本地的收件箱中, 具体目录是: 用户名/邮件帐号名/inbox/Mail对象的uuid.xml
	private void saveToInBox(List<Mail> newMails) {
		for (Mail mail : newMails) {
			//生成xml来存放这些新的邮件
			systemHandler.saveInBox(mail, this.ctx);
		}
	}

	private void saveToSpamBox(List<Mail> newMails) {
		for (Mail mail : newMails) {
			//生成xml来存放这些新的邮件
			systemHandler.saveSpamBox(mail, this.ctx);
		}
	}

	//在已发送的集合中添加一个邮件对象
	public void addSentMail(Mail mail) {
		this.sentMails.add(0, mail);
		refreshTable();
	}

	//在发件箱的集合中添加一个邮件对象
	public void addOutMail(Mail mail) {
		this.outMails.add(0, mail);
		refreshTable();
	}

	//在草稿箱的集合中添加一个邮件对象
	public void addDraftMail(Mail mail) {
		this.draftMails.add(0, mail);
		refreshTable();
	}

	//刷新列表的方法, 参数是不同的数据
	public void refreshTable() {
		//		DefaultTableModel tableModel = (DefaultTableModel) this.mailListTable.getModel();
		//		tableModel.setDataVector(createViewDatas(this.currentMails), getListColumn());
		//		setTableFace();
	}

	//当读取邮件后将图片改变为打开信封图片
	private void openEnvelop() {
		//		int row = this.mailListTable.getSelectedRow();
		//		int column = this.mailListTable.getColumn("打开").getModelIndex();
		//		this.mailListTable.setValueAt(this.envelopOpen, row, column);
		//		//重新保存邮件状态到xml文件
		//		this.systemHandler.saveMail(this.currentMail, this.ctx);
	}

	/*
	 * 设置方法， 打开设置界面
	 */
	private void setup() {

	}

	//可以让外界重新设界邮箱上下文
	public void setMailContext(MailContext ctx) {
		this.ctx = ctx;
	}

	public MailContext getMailContext() {
		return this.ctx;
	}

	public MailLoader getMailLoader() {
		return mailLoader;
	}

	public void setMailLoader(MailLoader mailLoader) {
		this.mailLoader = mailLoader;
	}

	private void write() {

	}

	//没有查看的邮件显示关闭的信封的图片地址
	private static String	CLOSE_ENVELOP_PATH	= "images/envelop-close.gif";
	//已经查看的邮件显示打开的信封的图片地址
	private static String	OPEN_ENVELOP_PATH		= "images/envelop-open.gif";

	//时间格式对象
	private DateFormat		dateFormat					= new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

	//将邮件数据集合转换成视图的格式
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Vector<Vector> createViewDatas(List<Mail> mails) {
		Vector<Vector> views = new Vector<Vector>();
		return views;
	}

	//格式时间
	private String formatDate(Date date) {
		return dateFormat.format(date);
	}

	//获得邮件列表的列名
	@SuppressWarnings("unchecked")
	private Vector getListColumn() {
		Vector columns = new Vector();
		columns.add("xmlName");
		columns.add("打开");
		columns.add("发件人");
		columns.add("主题");
		columns.add("日期");
		columns.add("大小");
		return columns;
	}

	private Object[] emptyListData = new Object[] {};

	public void stop() {
		timer.cancel();
	}

}

/**
 * 邮件接收的task对象
 * 
 * @author yangenxiong
 * 
 */
class ReceiveTask extends TimerTask {

	private MainFrame mainFrame;

	public ReceiveTask(MainFrame mainFrame) {
		this.mainFrame = mainFrame;
	}

	public void run() {
		try {
			this.mainFrame.getMailContext().getStore();
			this.mainFrame.receive();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("发生异常, 不接收");
		}
	}

}
